package com.grechur.wanandroidcompose.viewmodel

import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import com.grechur.wanandroidcompose.bean.navi.NavigationBean
import com.grechur.wanandroidcompose.http.service.NavigationService
import com.grechur.wanandroidcompose.http.NetworkRequest

class NavigationViewModel(application: Application) : AndroidViewModel(application) {
    var navigationBeans by mutableStateOf(Result.success(listOf<NavigationBean>()))
        private set

    suspend fun getNavigation() {
        val result = try {
            val service = NetworkRequest.getService(getApplication(), NavigationService::class.java)
            val navigation = service.getNavigation()
            navigation.let { baseData ->
                if (baseData.errorCode == 0) {
                    baseData.data.takeUnless { it.isNullOrEmpty() }?.let {
                        Result.success(it)
                    }?:Result.success(listOf())
                } else {
                    Result.failure(IllegalArgumentException("error code ${baseData.errorCode} msg ${baseData.errorMsg}"))
                }
            }
        } catch (e: Exception) {
            Result.failure(IllegalArgumentException("网络请求失败"))
        }
        navigationBeans = result
    }
}